﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Collections;
using Knihotoc_WP8.Data;
using Knihotoc_WP8.CustomControls;
using Knihotoc_WP8.Settings;
using Knihotoc_WP8.Misc;

namespace Knihotoc_WP8.Pages
{
    public partial class BookListPage : PhoneApplicationPage
    {
        public BookListPage()
        {
            this.InitializeComponent();

            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("AddBookButtonLabel");
            (ApplicationBar.Buttons[1] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("SettingsButtonLabel");
        }

        private IEnumerable returnBookSource()
        {
            List<Book> booksSource = new List<Book>();

            //foreach (AzureServiceReference.Book book in lb)
            //{
            //    booksSource.Add(new Book(book.ID, book.Title, book.Author, book.ImageLink));
            //}

            for (int i = 0; i < booksSource.Count; ++i)
            {
                booksSource[i].ImageThumbnailVisibility = CurrentSettings.Instance.BookListThumbnailsVisibility;
            }

            booksSource.Sort((x, y) => string.Compare(x.Title, y.Title));

            IEnumerable booksByTitle;

            switch (CurrentSettings.Instance.BookListOrderingOrder)
            {
                case OrderingOrder.ascending:
                    booksByTitle = from book in booksSource
                                   group book by book.TitleFirstLetter into c
                                   orderby c.Key ascending
                                   select new Group<Book>(c.Key, c);
                    break;

                case OrderingOrder.descending:
                    booksByTitle = from book in booksSource
                                   group book by book.TitleFirstLetter into c
                                   orderby c.Key descending
                                   select new Group<Book>(c.Key, c);
                    break;

                default:
                    throw new ArgumentOutOfRangeException("This value of the enum is not valid!");
            }

            return booksByTitle;
        }

        private IEnumerable<Book> GetTestData()
        {
            List<Book> booksSource = new List<Book>() { new Book(1, "Test1", "Tester1", "http://1.bp.blogspot.com/-WqzXH6Zp0hw/Tmey6eXlVsI/AAAAAAAAA3E/x76nMr5wo7M/s1600/Books.jpg", "432421", 100, 10, 10) };

            return booksSource;
        }

        private static List<Group<T>> GetItemGroups<T>(IEnumerable<T> itemList, Func<T, string> getKeyFunc)
        {
            IEnumerable<Group<T>> booksByTitle;

            switch (CurrentSettings.Instance.BookListOrderingOrder)
            {
                case OrderingOrder.ascending:
                    booksByTitle = from item in itemList
                                   group item by getKeyFunc(item) into g
                                   orderby g.Key ascending
                                   select new Group<T>(g.Key, g);
                    break;

                case OrderingOrder.descending:
                    booksByTitle = from item in itemList
                                   group item by getKeyFunc(item) into g
                                   orderby g.Key descending
                                   select new Group<T>(g.Key, g);
                    break;

                default:
                    throw new ArgumentOutOfRangeException("This value of the enum is not valid!");
            }

            return booksByTitle.ToList();
        }
        
        // TODO - remove this method - just for testing
        private List<Group<Book>> GetTestBooks()
        {
            IEnumerable<Book> testData = GetTestData();

            return GetItemGroups(testData, c => c.TitleFirstLetter);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
                List<Group<Book>> testBooks = GetTestBooks();
                this.foundBooksLongListSelector.ItemsSource = testBooks;
            }
            catch
            {   // TODO, log
                return;
            }
        }

        #region User input 
        private void BookItemTemplate_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            int bookID = ((GridID)sender).ID;

            NavigationService.Navigate(new Uri("/Pages/BookDetailPage.xaml?BookID=" + bookID.ToString(), UriKind.Relative));
        }

        private void FindBookButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BookFindPage.xaml", UriKind.Relative));
        }

        private void SettingsApplicationBarButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BooklistSettingsPage.xaml", UriKind.Relative));
        }
        #endregion        
    }
}